package moldat;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Diese Klasse verarbeitet alle Anfragen die von der 'HomePage' gestellt
 * werden. Ueber dieses Servlet werden Querys an die Datenbank weitergeleitet
 * und die Ergebnisse der Anfragen aufbereitet, sodass sie im HTML-Dokument
 * angezeigt werden können. Ausserdem wird die 'Query-History' ueber dieses
 * Servlet geregelt.
 *
 * @author Marc Zoeller
 */
public class HomeServlet extends HttpServlet {

    /**
     * Verarbeitet alle Post- und Get-Requests an dieses Servlet.
     *
     * @param request HTML-Request des Clients
     * @param response HTML-Response des Servers
     * @throws ServletException
     * @throws IOException
     */
    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        request.setAttribute("title", "Home");

        if (request.getParameter("querystring") != null) {
            try {
                String query = (String) request.getParameter("querystring");
                SQLiteDB.addQuery(query);
                ResultSet result = SQLiteDB.executeQuery(query);
                ResultSetMetaData metaData = result.getMetaData();
                int columnNr = metaData.getColumnCount();

                //Bestimmt die Reihenfolge der Spalten
                List<String> columnNames = new ArrayList<String>();
                for (int i = 1; i <= columnNr; i++)
                    columnNames.add(metaData.getColumnName(i));

                //Bearbeitet des ResultSet zur Ausgabe auf
                List<List<String>> results = new ArrayList<List<String>>();
                while (result.next()) {
                    List<String> values = new ArrayList<String>();
                    for (int i = 1; i <= columnNr; i++) {
                        if (metaData.getColumnType(i) == java.sql.Types.INTEGER)
                            values.add("" + result.getInt(i));
                        if (metaData.getColumnType(i) == java.sql.Types.VARCHAR)
                            values.add(result.getString(i));
                    }
                    results.add(values);
                }
                request.setAttribute("columnNames", columnNames);
                request.setAttribute("result", results);
            } catch (SQLException ex) {
                if (ex.getMessage().equals("query does not return ResultSet"))
                    request.setAttribute("error", "Finished.");
                else {
                    System.out.println("Error processing query: " + ex.getMessage());
                    request.setAttribute("error", ex.getMessage());
                }
            }
            context.getNamedDispatcher("QueryPage").forward(request, response);
        }
        else {
            //Laedt die Query-History
            try {
                ResultSet latestQuerys = SQLiteDB.getQueryHistory();
                if (latestQuerys != null) {
                    List<String> queryResult = new ArrayList<String>();
                    while (latestQuerys.next())
                        queryResult.add(latestQuerys.getString("history"));
                    request.getSession().setAttribute("queryhistory", queryResult);
                }
            } catch (SQLException ex) {
                System.out.println("Error loading queryhistory: " + ex.getMessage());
            }
            context.getNamedDispatcher("HomePage").forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
